package com.origon360.converters;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.origon.entities.Language;
import com.origon360.Services.ShopService;

@FacesConverter(value = "languageConverter")
@ManagedBean(name = "languageConverter")
@SessionScoped
public class LanguageConverter implements Converter {

	@EJB
	private ShopService shopService;

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {

		System.out.println("###### " + value);

		if (value == null || value.isEmpty()) {
			System.out.println("The null language is: " + value);
			return null;
		}

		Language lang = shopService.findLanguageByName(value);
		return lang;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value == null) {
			return null;
		}

		if (value instanceof Language) {
			return ((Language) value).getName();
		}

		System.out.println("Language converter result: " + value);
		return value.toString();

	}

}
